package org.luxor.commons.openfeign.component;

import feign.Util;
import feign.hystrix.FallbackFactory;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 全局一致的熔断故障处理方法
 *
 * @author Mr.Yan  @date: 2020/12/28
 */
public class HystrixFallbackFactory<T> implements FallbackFactory<T> {
    private final Logger logger;
    private final T constant;

    public HystrixFallbackFactory(T constant) {
        this(constant, Logger.getLogger(Default.class.getName()));
    }

    HystrixFallbackFactory(T constant, Logger logger) {
        this.constant = Util.checkNotNull(constant, "fallback");
        this.logger = Util.checkNotNull(logger, "logger");
    }

    @Override
    public T create(Throwable cause) {
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "fallback due to: " + cause.getMessage(), cause);
        }
        return constant;
    }

    @Override
    public String toString() {
        return constant.toString();
    }
}
